﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
using UnityEngine;

public class XmlDataMgr
{
    private static XmlDataMgr instance = new XmlDataMgr();
    public static XmlDataMgr Instance => instance;
    private XmlDataMgr() { }

    public void SaveData(object data, string fileName)
    {
        //获取路径
        string path = Application.persistentDataPath + "/" + fileName + ".xml";
        //存储文件
        using (StreamWriter write = new StreamWriter(path))
        {
            //序列化
            XmlSerializer s = new XmlSerializer(data.GetType());
            s.Serialize(write, data);
        }
    }

    public object LoadData(Type type, string fileName)
    {
        //获取路径
        string path = Application.persistentDataPath + "/" + fileName + ".xml";
        if (!File.Exists(path))
            path = Application.streamingAssetsPath + "/" + fileName + ".xml";
        if (!File.Exists(path))
            return Activator.CreateInstance(type);

        //读取数据
        using (StreamReader reader = new StreamReader(path))
        {
            XmlSerializer s = new XmlSerializer(type);
            return s.Deserialize(reader);
        }
    }

}
